package com.example.demo.service;

import com.example.demo.model.RegionStats;
import com.google.gson.Gson;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service

public class Finddata implements InitializingBean {


    private static final String url="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats=new ArrayList<RegionStats>();
    private int sum=0;
    private int differ;
    private String time ;

    public List<RegionStats> getAllRegionStats(Model model)
    {
        model.addAttribute("item",allRegionStats);
        model.addAttribute("sum",sum);
        model.addAttribute("differ",differ);
        model.addAttribute("nowTime",time);
        return allRegionStats;
    }

    public List<RegionStats>findcountry(Model model, String country){
        differ=0;
        sum=0;
        List<RegionStats> B=new ArrayList<RegionStats>();
        B=allRegionStats.stream().filter(regionStats -> regionStats.getCountry().equals(country)).collect(Collectors.toList());
        model.addAttribute("item",B);
        for(int i=0;i<B.size()-1;i++)
        {
            sum+=B.get(i).getLatestTotalCases();
            differ+=B.get(i).getDiffFromPrevDay();
        }
        model.addAttribute("sum",sum);
        model.addAttribute("differ",differ);
        model.addAttribute("nowTime",time);
        model.addAttribute("country",country);
       return allRegionStats;
    }

    @Scheduled(cron="0 0 1 * * *")
    public List<RegionStats> fetchdata( )throws IOException {
            differ=0;
            sum=0;
            DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date nowTime = new Date();
            time=dFormat.format(nowTime);
            String uriTemplate="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
            URI uri= UriComponentsBuilder.fromUriString(uriTemplate).build(42);
            RequestEntity<Void> requestEntity = RequestEntity.get(uri)
                    .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36"))
                    .build();
            ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, org.springframework.core.io.Resource.class);
            Resource body = exchange.getBody();
            InputStream a= body.getInputStream();
            Reader in=new InputStreamReader(a);
            Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
            for(CSVRecord record : records){
                RegionStats region=new RegionStats();
                region.setState(record.get(0));/*获取地区*/
                region.setCountry(record.get(1));/*获取国家*/
                region.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
                region.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
                sum+=Integer.parseInt(record.get(record.size()-1));
                differ+=Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2));
                allRegionStats.add(region);
        }
        return allRegionStats;
    }




    @Override
    public void afterPropertiesSet() throws Exception {
        fetchdata();
    }
}
